package com.rgst.comm;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * Created by tancw on 2017/3/23.
 */
public class SearchParam {
    private int start = 0;
    private int limit = 15;
    private int pageNo;
    private Map<String, Object> sp = new HashMap<String, Object>();
    private Map<String, Object> spDown;

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public int getPageNo() {
        return pageNo;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    public Map<String, Object> getSp() {
        sp.put("limit", limit);
        sp.put("start", start);
        return sp;
    }

    public void setSp(Map<String, Object> sp) {
        this.sp = sp;
    }

    public Map<String, Object> getSpDown() {
        if (sp != null) {
            sp.remove("limit");
            sp.remove("start");
        }
        Map<String, Object> param = new HashMap<>();
        for (Map.Entry<String, Object> entry : this.sp.entrySet()) {
            if (entry.getValue() == null || entry.getValue() == "") {
                continue;
            }
            param.put(entry.getKey(), entry.getValue());
        }
        return param;
    }

    public Pageable getPageable() {
        return PageRequest.of(this.getStart(), this.getLimit());
    }

    public Pageable getPageable(Sort sort) {
        return PageRequest.of(this.getPageNo(), this.getLimit(), sort);
    }

    public Example getParam(Class<?> clazz) {
        Object bean = null;
        try {
            bean = clazz.newInstance();
            BeanUtils.populate(bean, getSpDown());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Example.of(bean);
    }

    public Example getParam(Class<?> clazz, ExampleMatcher exampleMatcher) {
        Object bean = null;
        try {
            bean = clazz.newInstance();
            BeanUtils.populate(bean, getSpDown());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Example.of(bean, exampleMatcher);
    }
}
